from fastapi import APIRouter, Depends, HTTPException, status, Request
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from datetime import timedelta
from typing import List
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import auth
import database
import schemas

router = APIRouter()
security = HTTPBearer()

# 依赖项：获取数据库会话
def get_db():
    db = database.SessionLocal()
    try:
        yield db
    finally:
        db.close()

# 依赖项：获取当前用户
async def get_current_user(
    credentials: HTTPAuthorizationCredentials = Depends(security),
    db: Session = Depends(get_db)
):
    token = credentials.credentials
    token_data = auth.verify_token(token)
    if token_data is None or token_data.username is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无效的认证令牌",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    user = auth.get_user_by_username(db, token_data.username)
    if user is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户不存在"
        )
    
    return user

# 依赖项：要求管理员权限
async def get_current_admin_user(
    current_user: database.User = Depends(get_current_user)
):
    return auth.require_admin(current_user)

@router.get("/positions", response_model=List[str])
async def get_positions():
    """获取职位选项列表"""
    return [position.value for position in schemas.PositionEnum]

@router.post("/register", response_model=schemas.UserResponse)
async def register(user: schemas.UserCreate, db: Session = Depends(get_db)):
    """用户注册"""
    # 限制只有管理员可以创建管理员账户
    if user.role == schemas.UserRole.admin:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无法创建管理员账户"
        )
    
    try:
        db_user = auth.create_user(db, user)
        return db_user
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="注册失败：" + str(e)
        )

@router.post("/login", response_model=schemas.Token)
async def login(user_credentials: schemas.UserLogin, request: Request, db: Session = Depends(get_db)):
    """用户登录"""
    user = auth.authenticate_user(db, user_credentials.username, user_credentials.password, request)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    access_token_expires = timedelta(minutes=auth.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = auth.create_access_token(
        data={"sub": user.username, "role": user.role}, expires_delta=access_token_expires
    )
    
    return {
        "access_token": access_token,
        "token_type": "bearer",
        "expires_in": auth.ACCESS_TOKEN_EXPIRE_MINUTES * 60,  # 转换为秒
        "user_role": user.role
    }

@router.get("/me", response_model=schemas.UserResponse)
async def get_current_user_info(current_user: database.User = Depends(get_current_user)):
    """获取当前用户信息"""
    return current_user

@router.post("/logout", response_model=schemas.Message)
async def logout():
    """用户登出（前端需要删除令牌）"""
    return {"message": "成功登出"}

@router.get("/verify", response_model=schemas.Message)
async def verify_token_endpoint(current_user: database.User = Depends(get_current_user)):
    """验证令牌是否有效"""
    return {"message": "令牌有效"} 